package krow.dev.gunpobus.control.http;

import java.io.ByteArrayInputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import krow.dev.gunpobus.control.parser.IHtmlParser;
import net.htmlparser.jericho.Source;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

/**
 * XmlRequest
 * @author syuan
 * @since 2014. 02. 27.	 
*/
public class HtmlRequest<T> extends Request<T> {

	private final T mHtmlParser;

	private final Listener<T> mListener;
	
	private Map<String, String> mParameters;

	public HtmlRequest(int method, String url, T htmlParser, Listener<T> listener, ErrorListener errorListener) {
		super(method, url, errorListener);
		mListener = listener;
		mHtmlParser = htmlParser;
	}

	public HtmlRequest(String url, T xmlParser, Listener<T> listener, ErrorListener errorListener) {
		this(Method.GET, url, xmlParser, listener, errorListener);
	}

	public HtmlRequest(String url, Map<String, String> parameters, T xmlParser, Listener<T> listener, ErrorListener errorListener){
		this(Method.POST, url, xmlParser, listener, errorListener);
		
		mParameters = parameters;
	}
	
	@Override
	protected void deliverResponse(T response) {
		mListener.onResponse(response);
	}

	@Override
	protected Map<String, String> getParams() throws AuthFailureError {
		
		return mParameters;
	}
	
	@Override
	public Map<String, String> getHeaders() throws AuthFailureError {
		Map<String, String> headers = super.getHeaders();
		
		if(headers == null || headers.equals(Collections.emptyMap())){
			headers = new HashMap<String, String>();
		}
		
		return headers;
	}
	
	@Override
	protected Response<T> parseNetworkResponse(NetworkResponse response) {
		try {

			Source source = new Source(new ByteArrayInputStream(response.data));
			((IHtmlParser)mHtmlParser).parse(source);
		} catch (Exception e) {
			return Response.error(new ParseError(e));
		}
		return Response.success(mHtmlParser, HttpHeaderParser.parseCacheHeaders(response));
	}

}
